#coding:utf-8
from mri import*
from FileHelper import*
from DataUtil import*
import sys,os

def trans(data):
    data /= 255
    return data

def create_data_np():
    dr_folder=r'F:\PaperCode\ur_k_result\s3\s1_pre'
    result = r'F:\PaperCode\lw\result\f_r\s3'
    fg = '\\'
    folders = FileHelper.get_folders(dr_folder)
    index = 0
    for folder in folders:
        t = FileHelper.get_files(folder,'.png')
        files=[]
        for i in range(len(t)):
            f = folder + fg + str(i)+'.png'
            files.append(f)
        imges = []
        for f in files:
            img = ImageHelper().read(f).data()
            imges.append(trans(img))
        rf = result+fg+str(index)+'.npy'
        r = np.array(imges)
        np.save(rf,r)
        index+=1
        print r.shape

# create_data_np()

def create_label_np():
    la_folder = r'F:\PaperCode\Dataset\Train'
    result=r'F:\PaperCode\lw\result\f_r\label'
    files = FileHelper.get_files(la_folder,'segmentation.mhd')
    index = 0
    fg = '\\'
    for f in files:
        d = MRI(f)
        rf = result+fg+str(index)+'.npy'
        d = np.array(d.imgArray())
        np.save(rf,d)
        index +=1
        print d.shape
# create_label_np()


def cal_c2():
    result=r'F:\PaperCode\lw\result\f_r\result.npy'
    data_folder = r'F:\PaperCode\lw\result\f_r\s1'
    label_folder = r'F:\PaperCode\lw\result\f_r\label'
    fg = '\\'
    res = []
    for i in range(50):
        fn1 = data_folder+fg+str(i)+'.npy'
        fn2 = label_folder+fg+str(i)+'.npy'
        data = np.load(fn1)
        label = np.load(fn2)
        r = Evaluator.c2all(data,label)
        print r
        res.append(r)
    res = np.array(res)
    np.save(result,res)
    
# cal_c2()

def cal_dice():
    result=r'F:\PaperCode\lw\result\f_r\dice_res_s1.npy'
    data_folder = r'F:\PaperCode\lw\result\f_r\res_s1'
    label_folder = r'F:\PaperCode\lw\result\f_r\label'
    fg = '\\'
    res = []
    for i in range(50):
        fn1 = data_folder+fg+str(i)+'.npy'
        fn2 = label_folder+fg+str(i)+'.npy'
        data = np.load(fn1)
        label = np.load(fn2)
        a = data[data>0].size
        b = label[label>0].size
        c = (data*label)
        c = c[c>0].size
        print (a,b,c)
        r = 2.0*c/(a+b)
        res.append(r)
        print (r)
    res = np.array(res)
    np.save(result,res)

# cal_dice()

def common_cal(section,func):
    result=r'F:\PaperCode\lw\result\dice_3^3.npy'
    data_folder = r'F:\PaperCode\lw\result\3d-ur\Result_3^3'
    label_folder = r'F:\PaperCode\lw\result\f_r\label'
    fg = '\\'
    res = []
    a,b = section
    for i in range(a,b):
        fn1 = data_folder+fg+str(i)+'.npy'
        fn2 = label_folder+fg+str(i)+'.npy'
        data = np.load(fn1)
        label = np.load(fn2)
        r = func(data,label)
        res.append(r)
    res = np.array(res) 
    np.save(result,res)

def cal_c2all(data,label):
    #计算准确率，精确率，召回率，F1
    def F1(TP,FN,FP,TN):
        return 2.0*TP/(2.0*TP+FP+FN)
    def Recall(TP,FN,FP,TN):
        return 1.0*TP/(TP+FN)
    def Precision(TP,FN,FP,TN):
        return 1.0*TP/(TP+FP)
    def Acc(TP,FN,FP,TN):
        return 1.0*(TP+TN)/label.size
    r1 = label - data
    FN = r1[r1>0].size
    FP = r1[r1<0].size
    r2 = label*data
    TP = r2[r2>0].size
    TN = label.size - (FN + FP+ TP)
    a= Acc(TP,FN,FP,TN)
    b =Precision(TP,FN,FP,TN)
    c = Recall(TP,FN,FP,TN)
    d = F1(TP,FN,FP,TN)
    print (a,b,c,d)
    return (a,b,c,d)

def cal_dice(data,label):
    a = data[data>0].size
    b = label[label>0].size
    c = (data*label)
    c = c[c>0].size
    r = 2.0*c/(a+b)
    print r
    return r

# common_cal((40,50),cal_c2all)
# common_cal((40,50),cal_dice)

# f = r'F:\PaperCode\lw\result\f_r\dice_s3.npy'
# a = np.load(f)
# print a

def create_csv_np(separator=","):
    fn = r'F:\PaperCode\ur_k_result\tensorboard\res1.csv'
    result = r'F:\PaperCode\lw\result\f_r\loss\tensorboard\loss_res1.npy'
    d=[]
    with open(fn,'r') as f:
        i = 1
        for line in f.readlines():
            if i == 1:
                i = 2
                continue
            line = line.strip()
            data = line.split(separator)
            data = data[2]
            data = float(data)
            d.append(data)
    np.save(result,np.array(d))
# create_csv_np()

def ur_3d_csv():
    fn = r'F:\PaperCode\3d-ur-result\result_on_validation\timecost(ms)_3^3_newdata.csv'
    result = r'F:\PaperCode\lw\result\3d-ur\timecost_3^3.npy'
    d=[]
    with open(fn,'r') as f:
        for line in f.readlines():
            line = line.strip()
            data = float(line)
            d.append(data)
    def sum(a,b):
        return a+b
    r = []
    for i in range(1,11):
        t = reduce(sum,d[8*(i-1):8*i])
        t /= 8.0
        r.append(t)
    np.save(result,np.array(r))
# ur_3d_csv()
# f = r'F:\PaperCode\lw\result\3d-ur\timecost_3^3.npy'
# a = np.load(f)
# print a


def create_data_Aug():
    #对原始数据进行旋转，左右翻折的数据旋转，产生7张图像
    fn = r'F:\PaperCode\slice\20\12.png'
    result = r'C:\Users\Administrator\Desktop\res'
    out1 = Image.open(fn)
    out2 = out1.transpose(Image.FLIP_LEFT_RIGHT)
    suffix,fg,index = '.png','\\',0
    for i in range(3):
        r = result+fg+str(index)+suffix
        out1 = out1.rotate(90)
        out1.save(r)
        index+=1
    out2.save(result+fg+str(index)+suffix)
    index +=1
    for i in range(3):
        r = result+fg+str(index)+suffix
        out2 = out2.rotate(90)
        out2.save(r)
        index+=1
# create_data_Aug()

def create_3d_data_np():
    #创建三维结果的npy
    dr_folder=r'F:\PaperCode\3d-ur-result\Result_removeSkip'
    result = r'F:\PaperCode\lw\result\3d-ur\Result_removeSkip'
    fg = '\\'
    files = FileHelper.get_files(dr_folder,'.mhd')
    index = 40
    for f in files:
        data = MRI(f).imgArray()
        fn = result+fg+str(index)+'.npy'
        np.save(fn,data)
        index+=1
        print data.shape

# create_3d_data_np()

def create_3d_result_img():
    s_folder = r'F:\PaperCode\lw\result\3d-ur\Result_removeSkip'
    d_folder = r'F:\PaperCode\3d-ur-result\image\removeSkip'
    fg = '\\'
    files = FileHelper.get_files(s_folder,'npy')
    from PIL import Image
    for i in range(40,50):
        fd = d_folder+fg+str(i)
        os.makedirs(fd)
        f = files[i-40]
        f = np.load(f)
        z,x,y = f.shape
        for i in range(z):
            fn = fd+fg+str(i)+'.png'
            data = f[i,:,:]
            data*=255
            img = Image.fromarray(data)
            img.save(fn)

# create_3d_result_img()
